/**
* This file is part of mobileworks.
*
* mobileworks is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* You should have received a copy of the GNU General Public License
* along with dev.clipall.  If not, see <http://www.gnu.org/licenses/>.
*
* https://code.google.com/p/mobileworks/
*/

/*
 * Logger.java
 * Created on February 5, 2008, 6:16 PM
 */

package log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Calendar;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;

/**
 *
 * @author Erol Hira
 */
public class Logger {
    
    private String file = "file:///root1/log";    
    private String url = "http://localhost:8084/MobileLoggerWEB/Logger";        
    
    private final boolean fileLog = false;
    private final String projectName = "Mui";
    
    private static Logger logger = new Logger();
    
    private final String ERROR = "ERROR";
    private final String DEBUG = "DEBUG";
    
    Connection conn;
    DataOutputStream out;
    DataInputStream in;
    
    private Logger() {
        
        Calendar cal = Calendar.getInstance();
        file += "-" + cal.get(Calendar.YEAR) + "-" + cal.get(Calendar.MONTH) + "-"+
                (cal.get(Calendar.DAY_OF_MONTH) + 1) + "-" + 
                cal.get(Calendar.HOUR_OF_DAY) + "_" + cal.get(Calendar.MINUTE) + "_" 
                + cal.get(Calendar.SECOND) + ".txt";                             
        
        init();
        
    }
    
    public static Logger getLogger(){                        
        logger.resetLogger();
        return logger;
    }
    
    private void init(){
        
        try {
            
            if(fileLog){
                FileConnection conn = (FileConnection) Connector.open(file, Connector.READ_WRITE);
                
                if (!conn.exists()) {
                    conn.create();
                }

                in = conn.openDataInputStream();
                out = conn.openDataOutputStream();
                
                this.conn = conn;
            }                                                 
            
        } catch (IOException ex) {
            closeConnection();            
        }
    }
    
    private void closeConnection(){
        
        if(in != null){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(out != null){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(conn != null){
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    private void resetLogger(){
        
        if(fileLog){
            
            FileConnection conn = (FileConnection) this.conn;
            
            if(conn == null || conn.isOpen() == false){
            
                init();

                try {                
                    int logSize = (int)conn.fileSize();
                    byte[] buf = new byte[logSize];
                    in.read(buf);
                    out.write(buf);
                    out.flush();
                } catch (IOException ex) {
                    closeConnection();
                }
            }
        }            
    }
    
    public synchronized void write(String methodName, String msg, String level) throws IOException{                
        
        if(fileLog){
            writeToFile(methodName, msg, level);
        } else {
            writeToNet(methodName, msg, level);
        }
    }
        
    public void writeToFile(String methodName, String msg, String level) throws IOException{
        Calendar cal = Calendar.getInstance();
        String timeStr = cal.get(Calendar.HOUR_OF_DAY) + ":" 
                + cal.get(Calendar.MINUTE) + ":" 
                + cal.get(Calendar.SECOND);
        
        String str = level + ": " + timeStr + " " + methodName + ": " + msg;                
        
        out.write(str.getBytes());
        out.write("\r\n".getBytes());
        
        out.flush();
    }
    
    public void writeToNet(String methodName, String msg, String level) throws IOException{
        
        HttpConnection hconn = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
        
        conn = hconn;
        
        hconn.setRequestMethod(HttpConnection.POST);
        
        out = hconn.openDataOutputStream();
        
        out.writeUTF(projectName);
        out.writeUTF(level);
        out.writeUTF(methodName);
        out.writeUTF(msg); 
        out.flush();
        
        closeConnection();
    }
    
    public void debug(final String methodName, final String msg){
        
        new Thread(){
            
            public void run(){
                try {
                    write(methodName, msg, DEBUG);                
                } catch (IOException ex) {
                    closeConnection();
                }                
            }
            
        }.start();
    }
    
    public void error(final String methodName, String msg, Throwable t){
        
        final String str = t.toString() + "\r\n" + msg;
        
        new Thread(){
            
            public void run(){
                try {
                    write(methodName, str, ERROR);                
                } catch (IOException ex) {
                    closeConnection();
                }                
            }
            
        }.start();
    }
}
